//
//  NSString+Number.h
//  SleepingElf
//
//  Created by karong on 2023/6/20.

#import "UIScrollView+ScrollMethod.h"

@implementation UIScrollView (ScrollMethod)

- (UIEdgeInsets)wc_contentInset {
    if (@available(iOS 11, *)) { return self.adjustedContentInset; }
    else { return self.contentInset; }
}

- (BOOL)wc_alreadyAtTop {
    if (((NSInteger)self.contentOffset.y) == -((NSInteger)self.wc_contentInset.top)) {
        return YES;
    }
    return NO;
}

- (BOOL)wc_alreadyAtBottom {
    if (!self.wc_canScroll) { return YES; }
    if (((NSInteger)self.contentOffset.y) == ((NSInteger)self.contentSize.height + self.wc_contentInset.bottom - CGRectGetHeight(self.bounds))) {
        return YES;
    }
    return NO;
}

- (BOOL)wc_canScroll {
    
    if (![self wc_CGSizeIsEmpty:self.bounds.size]) { return NO; }
    
    BOOL canVerticalScroll = self.contentSize.height + [self wc_UIEdgeInsetsGetVerticalValue:self.wc_contentInset] > CGRectGetHeight(self.bounds);
    BOOL canHorizontalScoll = self.contentSize.width + [self wc_UIEdgeInsetsGetHorizontalValue: self.wc_contentInset] > CGRectGetWidth(self.bounds);
    return canVerticalScroll || canHorizontalScoll;
}

- (void)wc_scrollToTopAnimated:(BOOL)animated {
    CGPoint off = self.contentOffset;
    off.y = 0 - self.wc_contentInset.top;
    [self setContentOffset:off animated:animated];
}

- (void)wc_scrollToTop {
    [self wc_scrollToTopAnimated:YES];
}

- (void)wc_scrollToBottemAnimated:(BOOL)animated {
    CGPoint off = self.contentOffset;
    off.y = self.contentSize.height - self.bounds.size.height + self.wc_contentInset.bottom;
    [self setContentOffset:off animated:YES];
}

- (void)wc_scrollToBottem {
    [self wc_scrollToBottemAnimated:YES];
}

- (void)wc_scrollToLeftAnimated:(BOOL)animated {
    CGPoint off = self.contentOffset;
    off.x = 0 - self.wc_contentInset.left;
    [self setContentOffset:off animated:animated];
}

- (void)wc_scrollToLeft {
    [self wc_scrollToLeftAnimated:YES];
}

- (void)wc_scrollToRightAnimated:(BOOL)animated {
    CGPoint off = self.contentOffset;
    off.x = self.contentSize.width - self.bounds.size.width + self.wc_contentInset.right;
    [self setContentOffset:off animated:animated];
}

- (void)wc_scrollToRight {
    [self wc_scrollToRightAnimated:YES];
}

- (void)wc_stopDeceleratingIfNeeded {
    if (self.decelerating) {
        [self setContentOffset:self.contentOffset animated:NO];
    }
}

- (BOOL)wc_CGSizeIsEmpty:(CGSize)size {
    return size.width <=0 || size.height <= 0;
}

- (CGFloat)wc_UIEdgeInsetsGetVerticalValue:(UIEdgeInsets)insets {
    return insets.top + insets.bottom;
}

- (CGFloat)wc_UIEdgeInsetsGetHorizontalValue:(UIEdgeInsets)insets {
    return insets.left + insets.right;
}

@end
